#####################
### Load Packages ###
#####################

library(haven)


# Set this Working Directory to the Folder with the Replication Files
#setwd("C:/Steven/GDrive/Research Files/Clark-Rogers/Descriptive Representation/APSR Final Submission/Replication")

###
# Functions
###

# Function to Clean Up STATA Estimates and Confidence Intervals
  CleanUp <- function(CurrentVariable)
    {
      CurrentVariable <- gsub("=","", CurrentVariable)
      CurrentVariable <- gsub("[/*]","", CurrentVariable)
      CurrentVariable <- gsub("\\(","", CurrentVariable)
      CurrentVariable <- gsub("\\)","", CurrentVariable)
      CurrentVariable <- gsub("\\]","", CurrentVariable)
      CurrentVariable <- gsub("\\[","", CurrentVariable)
      CurrentVariable <- as.numeric(CurrentVariable)
      return(CurrentVariable)
    }

  
# Function to Extract and Clean Estimate and Confidence Interval
  
  ExtractEstimates <- function(CurrentLabel, CurrentEstimate, CurrentCI)
    {
    
    LowerBound <- sapply(strsplit(CurrentCI, ","), "[", 1)
    UpperBound <- sapply(strsplit(CurrentCI, ","), "[", 2)
    
    CurrentEstimates <- data.frame(matrix(NA, 1,0))
      CurrentEstimates$Label <- CurrentLabel
      CurrentEstimates$Coefficient <- CleanUp(CurrentEstimate)
      CurrentEstimates$LowerBound <-  CleanUp(LowerBound)
      CurrentEstimates$UpperBound <-  CleanUp(UpperBound)
    
    return(CurrentEstimates)
    }

# Function to Create Base Plot
  BasePlot <- function(CurrentCoefficient, CurrentYLocation)
  {
    plot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation,
         type="n",
         ylab=" ",
         xaxt="n",
         yaxt="n",
         cex.main=1.3,
         xlim=c(-.022,.022),
         ylim=c(0,3),
         cex.axis=.7,
         xaxs = "i", # Removes Inner Margin
         yaxs = "i", # Removes Inner Margin
         #main="Probabilities of Incumbents Being Contested by Party Membership",
         xlab=" ",
         family="B"
    )
    abline(v=0, col="grey", lty=2)
    
    # Make the ticks on the line
    axis(side=1, at=c(-0.02, -0.01, 0, 0.01, 0.02), labels=c("", "", "", "", ""))
    
    # Put the numbers higher than R wants with ticks
    axis(side=1, at=c(-0.02, -0.01, 0, 0.01, 0.02), labels=c("-0.02", "-0.01", "0", "0.01", "0.02"), line=-.5, tick="FALSE", cex.axis=.75)
    
    
  }

# Function to Create Completely Blank Plot
  BlankPlot <- function(CurrentCoefficient, CurrentYLocation)
  {
    plot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation,
         type="n",
         ylab=" ",
         xaxt="n",
         yaxt="n",
         cex.main=1.3,
         xlim=c(-.022,.022),
         ylim=c(0,3),
         cex.axis=.9,
         xaxs = "i", # Removes Inner Margin
         yaxs = "i", # Removes Inner Margin
         #main="Probabilities of Incumbents Being Contested by Party Membership",
         xlab=" ",
         family="B",
         bty="n"
    )
  }
  
##
# Stauffer Estimates 
##
  
  # Women Congress - Belief
  
    StaufferCongressRaw <- read.csv("Scripts/Figures/Estimates/Stauffer-Congress.csv")
      colnames(StaufferCongressRaw) <- c("VariableName", "Estimates")

      # Determine the Rows of the Coefficient and Standard Error
      StaufferCongressRaw$RowNumber <- rownames(StaufferCongressRaw)
      EstimateRowNumber <- as.numeric(StaufferCongressRaw$RowNumber[StaufferCongressRaw$VariableName=="=Belief_WomenCongress"])
        StaufferCongress_BeliefEstimate <- StaufferCongressRaw$Estimates[EstimateRowNumber]
        StaufferCongress_ConfidenceInterval <- StaufferCongressRaw$Estimates[EstimateRowNumber+1]
        
        StaufferEstimates <- ExtractEstimates("Stauffer - Congress - Women - Belief", StaufferCongress_BeliefEstimate, StaufferCongress_ConfidenceInterval)
    
    # Women State Leg   
    
      StaufferStateLegRaw <- read.csv("Scripts/Figures/Estimates/Stauffer-StateLeg.csv")
      colnames(StaufferStateLegRaw) <- c("VariableName", "Estimates")
      
      # state is true descriptive representation
      # state_guess is perceived descriptive representation
      
      # Factual Estimates
      StaufferStateLegRaw$RowNumber <- rownames(StaufferStateLegRaw)
      FactualEstimateRowNumber <- as.numeric(StaufferStateLegRaw$RowNumber[StaufferStateLegRaw$VariableName=="=True_WomenStateLeg"])
        StaufferStateLeg_FactualEstimate <- StaufferStateLegRaw$Estimates[FactualEstimateRowNumber]
        StaufferStateLeg_FactualConfidenceInterval <- StaufferStateLegRaw$Estimates[FactualEstimateRowNumber+1]
    
      CurrentEstimates <- ExtractEstimates("Stauffer - StateLeg - Women - Factual", StaufferStateLeg_FactualEstimate, StaufferStateLeg_FactualConfidenceInterval)
      StaufferEstimates <- rbind(StaufferEstimates, CurrentEstimates)  
  
      # Belief Estimates
      StaufferStateLegRaw$RowNumber <- rownames(StaufferStateLegRaw)
      BeliefEstimateRowNumber <- as.numeric(StaufferStateLegRaw$RowNumber[StaufferStateLegRaw$VariableName=="=Belief_WomenStateLeg"])
        StaufferStateLeg_BeliefEstimate <- StaufferStateLegRaw$Estimates[BeliefEstimateRowNumber]
        StaufferStateLeg_BeliefConfidenceInterval <- StaufferStateLegRaw$Estimates[BeliefEstimateRowNumber+1]
        
        CurrentEstimates <- ExtractEstimates("Stauffer - StateLeg - Women - Belief", StaufferStateLeg_BeliefEstimate, StaufferStateLeg_BeliefConfidenceInterval)
        StaufferEstimates <- rbind(StaufferEstimates, CurrentEstimates)  
    
      StaufferEstimates$YLocation <- 2

##
# Rogers Estimates
##
    ###
    # Women
    ###
      
      # Women Congress - Belief
      
      RogersCongressRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-Congress-Women.csv")
      colnames(RogersCongressRaw) <- c("VariableName", "Estimates")
      
      # Determine the Rows of the Coefficient and Standard Error
      RogersCongressRaw$RowNumber <- rownames(RogersCongressRaw)
      EstimateRowNumber <- as.numeric(RogersCongressRaw$RowNumber[RogersCongressRaw$VariableName=="=Belief_WomenCongress"])
      RogersCongress_BeliefEstimate <- RogersCongressRaw$Estimates[EstimateRowNumber]
      RogersCongress_ConfidenceInterval <- RogersCongressRaw$Estimates[EstimateRowNumber+1]
      
      RogersEstimates <- ExtractEstimates("Rogers - Congress - Women - Belief", RogersCongress_BeliefEstimate, RogersCongress_ConfidenceInterval)
      
      # Women State Leg 
      
      RogersStateLegRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-StateLeg-Women.csv")
      colnames(RogersStateLegRaw) <- c("VariableName", "Estimates")

      
      # Factual Estimates
        RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
        FactualEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=True_WomenStateLeg"])
        RogersStateLeg_FactualEstimate <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber]
        RogersStateLeg_FactualConfidenceInterval <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Women - Factual", RogersStateLeg_FactualEstimate, RogersStateLeg_FactualConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)
      
      # Belief Estimates
        RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
        BeliefEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=Belief_WomenStateLeg"])
        RogersStateLeg_BeliefEstimate <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber]
        RogersStateLeg_BeliefConfidenceInterval <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Women - Belief", RogersStateLeg_BeliefEstimate, RogersStateLeg_BeliefConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
    
    ###
    # Blacks
    ###
      
      # Blacks Congress - Belief
      
      RogersCongressRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-Congress-Blacks.csv")
      colnames(RogersCongressRaw) <- c("VariableName", "Estimates")
      
      # Determine the Rows of the Coefficient and Standard Error
      RogersCongressRaw$RowNumber <- rownames(RogersCongressRaw)
      EstimateRowNumber <- as.numeric(RogersCongressRaw$RowNumber[RogersCongressRaw$VariableName=="=Belief_BlackCongress"])
      RogersCongress_BeliefEstimate <- RogersCongressRaw$Estimates[EstimateRowNumber]
      RogersCongress_ConfidenceInterval <- RogersCongressRaw$Estimates[EstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - Congress - Blacks - Belief", RogersCongress_BeliefEstimate, RogersCongress_ConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
      
      # Blacks State Leg
      
      RogersStateLegRaw <- read.csv("Scripts/Figures/Estimates/Clark-Rogers-StateLeg-Blacks.csv")
      colnames(RogersStateLegRaw) <- c("VariableName", "Estimates")
      
      # Factual Estimates
      RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
      FactualEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=True_BlackStateLeg"])
      RogersStateLeg_FactualEstimate <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber]
      RogersStateLeg_FactualConfidenceInterval <- RogersStateLegRaw$Estimates[FactualEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Blacks - Factual", RogersStateLeg_FactualEstimate, RogersStateLeg_FactualConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)
      
      # Belief Estimates
      RogersStateLegRaw$RowNumber <- rownames(RogersStateLegRaw)
      BeliefEstimateRowNumber <- as.numeric(RogersStateLegRaw$RowNumber[RogersStateLegRaw$VariableName=="=Belief_BlackStateLeg"])
      RogersStateLeg_BeliefEstimate <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber]
      RogersStateLeg_BeliefConfidenceInterval <- RogersStateLegRaw$Estimates[BeliefEstimateRowNumber+1]
      
      CurrentEstimates <- ExtractEstimates("Rogers - StateLeg - Blacks - Belief", RogersStateLeg_BeliefEstimate, RogersStateLeg_BeliefConfidenceInterval)
      RogersEstimates <- rbind(RogersEstimates, CurrentEstimates)  
      
      RogersEstimates$YLocation <- 1
      
      
###
# Plot Time
###
      
      
tiff(filename = "Figures/Figure.tiff", width = 7, height = 1.5, units = "in", pointsize = 12, res=1000)

      # Ultimately Going to Create Plot that is 2 rows by 4 Columns
      
      windowsFonts(
        A=windowsFont("Arial Black"),
        B=windowsFont("Cambria"),
        C=windowsFont("Comic Sans MS"),
        D=windowsFont("Symbol")
      )
      

      #par(family="B",
      #    mai=c(.5,.1,.1,.1), 
      #    mfrow=c(3,5))

      par(family="B",
          mai=c(.1,.1,.1,.1),
          mar=c(1.5,1,.9,1))
      
      nf <- layout(
        matrix(c(1,2,3,4,5,6,7,8,9,10), ncol=5, byrow=TRUE), 
        widths=c(1.5,1.5,1.5,1.5,1.5), 
        heights=c(3,3)
      )
      
##
# First Row of Beliefs
##
      
      # Label Plot
      
      BlankPlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)      
      
      text(0, 2.75, "Coefficients for Perceptions of", cex=.7)
      text(0, 2.1, "Descriptive Representation", cex=.7)
      
      legend(-.022,1.75, ncol=1,
             c("Stauffer Estimates", "Current Study Estimates"),
             pch=c(1,2), lwd=c(1,1), col=c("black", "black"),
             cex=.7, bty="n")    
          
      # Women in Congress Plot ~ Belief Only
          BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)

          title(main = "Women in Congress", cex.main = .9)
          
        # Stauffer
          CurrentEstimates <- subset(StaufferEstimates, StaufferEstimates$Label=="Stauffer - Congress - Women - Belief")
          segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
          points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
          
          
        # Rogers
          CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - Congress - Women - Belief")
          segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
          points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
            
      # Women in State Leg Plot - Belief Only
          BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)
          
          title(main = "Women in State Leg.", cex.main = .9)
          
          
          # Stauffer
              CurrentEstimates <- subset(StaufferEstimates, StaufferEstimates$Label=="Stauffer - StateLeg - Women - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
              
          # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Women - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in Congress Plot ~ Belief Only
              BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)
              title(main = "Blacks in Congress", cex.main = .9)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - Congress - Blacks - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in State Leg Plot ~ Belief Only
              BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)
              title(main = "Blacks in State Leg.", cex.main = .9)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Blacks - Belief")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
##
# Second Row of Factual
##
        # Label Plot
            BlankPlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)      
            
            text(0, 2.75, "Coefficients for Actual", cex=.7)
            text(0, 2.1, "Descriptive Representation", cex=.7)

            legend(-.022,1.75, ncol=1,
                   c("Stauffer Estimates", "Current Study Estimates"),
                   pch=c(1,2), lwd=c(1,1), col=c("black", "black"),
                   cex=.7, bty="n")    
            
        # Women in Congress Plot ~ Factual Only
            BlankPlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)      
            

        
        # Women in State Leg Plot - Factual Only
              BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)
              
              # Stauffer
              CurrentEstimates <- subset(StaufferEstimates, StaufferEstimates$Label=="Stauffer - StateLeg - Women - Factual")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=1, cex=.75)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Women - Factual")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
        # Blacks in Congress Plot ~ Factual Only
              BlankPlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)      
              
        # Blacks in State Leg Plot ~ Belief Only
              BasePlot(StaufferEstimates$Coefficient, StaufferEstimates$YLocation)
              
              # Rogers
              CurrentEstimates <- subset(RogersEstimates, RogersEstimates$Label=="Rogers - StateLeg - Blacks - Factual")
              segments(CurrentEstimates$LowerBound, CurrentEstimates$YLocation, CurrentEstimates$UpperBound, CurrentEstimates$YLocation)
              points(CurrentEstimates$Coefficient, CurrentEstimates$YLocation, pch=2, cex=.75)
              
      dev.off()        
              
              